package com.etc.demo.controller;

import com.etc.demo.utils.JdbcUtils;
import com.sun.org.apache.bcel.internal.generic.Select;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;

/**
 * 用户登录控制器
 */
@RestController
public class LoginController {

    /**
     * 登录接口
     * @param username 用户名
     * @param password 密码
     * @return
     * @throws SQLException
     */
    //spring mvc 技术 MVC是模型(model)-视图(view)-控制器(controller)的缩写 将业务
    //逻辑集中到一个部件里边 MVC 方法作为驱动 接受get（post）请求 前后端参数必须一样
      @GetMapping("login")
      public String login(String username ,String password) throws SQLException{
           if(username == null || username.length() <=0) {
               return "请输入用户名";
           }
           if(password == null || password.length() <=0) {
               return "请输入密码";
           }
           Connection con = JdbcUtils.getConnection();
           PreparedStatement p = con.prepareStatement("select * from user where username= ?");
           p.setString(1,username);
           ResultSet resultSet = p.executeQuery();
           String password1 = "";
           while(resultSet.next()){
               password1 = resultSet.getString("password");
           }
           if(password1.equals(password)){
               return "1";
           }else {
               return "0";
           }
       }

    /**
     * 用户新增
     * @param username 用户名
     * @param password 密码
     * @param loginname 登录名
     * @return
     * @throws SQLException
     */
         @GetMapping("add")
         public String userAdd(String username,String password,String loginname) throws SQLException {

           if(username == null || username.length() <=0){
               return "请输入用户名";
           }
           if(username == null || password.length() <=0){
               return "请输入密码";
           }
           if(username == null || loginname.length() <=0){
               return "请输入名字";
           }

           //获取连接对象
           Connection con = JdbcUtils.getConnection();
           //获取执行器
           PreparedStatement p = con.prepareStatement("insert into user(username,password,loginname) value(?,?,?)");
           p.setString(1,username);
           p.setString(2,password);
           p.setString(3,loginname);
           int result = p.executeUpdate();
           if(result == 1){
               return  "1";
           }else{
               return "0";
           }
       }
}
